import Taro, {Component} from '@tarojs/taro'
import {View} from '@tarojs/components'
import { AtTabs, AtTabsPane } from 'taro-ui'
import Cata from './cata'
import FoodList from './foodlist'
import './food.scss'

export default class Food extends Component {
    constructor () {
        super(...arguments);
        this.state = {
            current: 0,
            tabList :
                [{ title: '点菜' },
                 { title: '评价' },
                 { title: '商家' }
                 ],
            selectCata:{},
            foodList:[],
            currentList:[]
        }
    }
    changeTab(value){
        this.setState({
            current: value
        })
    }
    //切换分类
    changeCata(selectCata){
        if(this.state.foodList.some(item=>item.pid == selectCata.id)){
            //不用加载数据，找到后扔给foodlist组件
            this.setState({
                currentList:this.state.foodList.filter(item=>item.pid == selectCata.id),
                selectCata:selectCata
            })
        }else{
            //需要加载数据
            this.setState({
                foodList:this.state.foodList.concat(this.getData(selectCata))
            },()=>{
                //加载成功后赋给currentList
                this.setState({
                    currentList:this.state.foodList.filter(item=>item.pid == selectCata.id),
                    selectCata:selectCata
                })
            })

        }
    }
    getData(selectCata){
        let count = Math.round(Math.random()*2);
        return Array.from(
            Array(Math.round(Math.random()*20)),(v,k)=>(
                {
                    price:Math.round(Math.random()*20),
                    sale:Math.round(Math.random()*50),
                    img:count,
                    pid:selectCata.id,
                    id:selectCata.id+"_"+k,
                    title:"分类"+selectCata.id+"菜品"+(k+1)
                }
                )
        )
    }
    render() {
        const {tabList,current,currentList,selectCata} = this.state;
        return (
            <View className='food'>
                <AtTabs current={current} tabList={tabList} onClick={this.changeTab.bind(this)}>
                    <AtTabsPane current={current} index={0} >
                       <View className='food_body'>
                           <Cata onChangeCata={this.changeCata.bind(this)}/>
                           <View className='foodList-wrap'>
                               <FoodList selectCata={selectCata} currentList={currentList}/>
                           </View>
                       </View>
                    </AtTabsPane>
                    <AtTabsPane current={current} index={1}>
                       评价
                    </AtTabsPane>
                    <AtTabsPane current={current} index={2}>
                        商家
                    </AtTabsPane>
                </AtTabs>
            </View>
        )
    }
}
